import json

from todo import Todo
from storage_mysql import TodoStorage
from flask import Flask, request

app = Flask(__name__)


app.config['JSON_AS_ASCII'] = False

storage = TodoStorage()
storage.init_db()


@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"


@app.route("/todos", methods=['GET'])
def list_todos():
    # return {"todos": [x.__dict__ for x in storage.get_list()]}
    if request.args['completed'] == '1':
        return {"todos": [x.__dict__ for x in storage.get_list() if x.completed]}
    elif request.args['completed'] == '0':
        return {"todos": [x.__dict__ for x in storage.get_list() if not x.completed]}
    elif request.args['completed'] :
        return {"todos": [x.__dict__ for x in storage.get_list()]}


@app.route("/todos", methods=['POST'])
def create_todo():

    if 'title' not in request.form:
        return '参数错误，必须提供 title 参数', 400
    todo = storage.create(request.form['title'])
    return todo.__dict__


@app.route("/todos/mark_completed", methods=['GET'])
def mark_completed():
    if 'id' not in request.args:
        return '参数错误，必须提供 todo_id 参数', 400
    todo_id = int(request.args['id'])
    todo = storage.mark_completed(todo_id)
    if todo is not None:
        return todo.__dict__
    else:
        return f'todo not found, todo_id={todo_id}', 404

@app.route("/todos/del", methods=['GET'])
def del_todo():
    if 'id' not in request.args:
        return "参数错误，必须提供 id参数", 400
    # todo_id = int(request.args['id'])
    # storage.del_todo(todo_id)
    todo_list = request.args['id']
    todo = storage.del_todo(todo_list)
    if todo is not None:
        return todo.__dict__
    else:
        return f'todo not found, todo_list={todo_list}', 404


if __name__ == '__main__':
    app.run()